#include"my_stdio.h"
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
mFILE* mfopen(const char* filename,const char* mode)
{
    int fd = -1;
    if(strcmp(mode,"r")==0)
    {
        fd = open(filename, O_RDONLY);
    }
    else if(strcmp(mode,"w")==0)//可读可写，没有则创建,有则清空
    {
        fd = open(filename,O_CREAT|O_RDONLY|O_TRUNC|O_WRONLY,0666 );
    }
    else if(strcmp(mode,"a")==0)
    {
        fd = open(filename,O_CREAT|O_RDONLY|O_APPEND,0666 );
    }
    if(fd<0)
        return NULL;
    mFILE* mf = (mFILE*)malloc(sizeof(mFILE));
    if(!mf){
        close(fd);
        return NULL;
    }
    mf->fileno = fd;
    mf->cap = SIZE;
    mf->size = 0;
    mf->flag = FLUSH_LINE;
    return mf;
}

void mfflush(mFILE* stream)
{
    if(stream->size>0)
    {
        // 写到内核文件的文件缓冲区中
        write(stream->fileno,stream->buffer,stream->size);
        //刷新外设（磁盘或显示器等文件）
        fsync(stream->fileno);
        stream->size = 0;
    }
}
void mfclose(mFILE* stream)
{
    if(stream->size>0)
        mfflush(stream);
    close(stream->fileno);
}
int mfwrite(const void* ptr,int num, mFILE* stream)
{
   //拷贝
    memcpy(stream->buffer+stream->size,ptr,num);
    stream->size+=num;
    //检查是否要刷到内核缓冲区
    if(stream->flag==FLUSH_LINE && stream->size>0 && stream->buffer[stream->size-1]=='\n')
    {
        mfflush(stream);
    }
    return num;
}
